<template>
  <div class="">
    <!-- 图片上传的两种方式
            1. 原生form表单上传 name属性一般都是file
                a) 同步上传,页面刷新
                b) 进度条 状态都不好控制
            2. ajax异步上传
                a) 可以实现异步上传
                b) 可以控制进度条

         -->
    <form action="http://bufan.cloud/admin/xy/upload/uploadImg" method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <button type="submit">提交</button>
    </form>
    <hr>
    <input type="file" accept=".png, .jpg, .jpeg" @change="handleFileChange($event)">
    <img :class="{succ:isSuc}" :src="tempImg" alt="">
    <hr>
    <h2>element upload 组建</h2>
    <el-upload
      ref="upload"
      class="upload-demo"
      action="/admin/xy/upload/uploadImg"
      :on-success="handleSuccess"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <img :src="tempImg" alt="">
  </div>
</template>

<script>
import axios from 'axios'
import config from '@/api/config'
export default {
  components: {

  },
  data() {
    return {
      tempImg: '',
      isSuc: false,
      fileList: []
    }
  },
  computed: {

  },
  created() {

  },
  mounted() {

  },
  methods: {
    handleFileChange(e) {
      var url = '/admin/xy/upload/uploadImg'
      // 获取事件触发的对象
      var target = e.target
      var files = target.files
      // file类型 不能直接上传  必须包装为 FormData类型
      var fd = new FormData()
      // 对fd添加key为file的文件,files[0]获取默认第一个元素
      fd.append('file', files[0])
      // 上传之前获取预览图片: 通过 window.URL.createObjectURL
      this.tempImg = window.URL.createObjectURL(files[0])
      // 后台或从 'file'的key中获取 file文件数据
      axios.post(url, fd).then(res => {
        console.log(res)
        if (res.data.url) {
          this.isSuc = true
        }
      })
      console.log(files)
    },
    handleSuccess(response, file, fileList) {
      console.log(response)
      this.tempImg = config.host + '/' + response.url
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped lang="scss">
    .succ{
        border: 2px solid green;
    }
</style>

